package com.zwj.spring_study.a05.postprocessor;

import com.zwj.spring_study.a05.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * bean的扫描与注册
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/6/9 23:00
 */
@Slf4j
public class ComponentScanPostProcessor2 implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            log.info("扫描注解start");
            //从Config类中，获取第一个匹配到的ComponentScan注解
            ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
            CachingMetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

            //组件名称生成器
            AnnotationBeanNameGenerator nameGenerator = new AnnotationBeanNameGenerator();
            if (componentScan == null) {
                return;
            }
            //遍历该路径下的类，判断是否被@Component注解或者其派生注解标识
            for (String basePackage : componentScan.basePackages()) {
                String path = "classpath*:" + basePackage.replace(".", "/") + "/**/*.class";
                log.info("类路径：" + path);
                PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
                Resource[] resources = resourcePatternResolver.getResources(path);
                for (Resource resource : resources) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    //是否存在@ComponentScan注解
                    boolean hasAnnotation = metadataReader.getAnnotationMetadata().hasAnnotation(Component.class.getName());
                    //是否存在@ComponentScan派生注解，如@Controller，@Service等注解
                    boolean hasMetaAnnotation = metadataReader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName());
                    if (hasAnnotation || hasMetaAnnotation) {
                        //将被标识的类注册到BeanFactory中，使其成为Bean
                        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(metadataReader.getClassMetadata().getClassName())
                                .getBeanDefinition();
                        if (configurableListableBeanFactory instanceof DefaultListableBeanFactory) {
                            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                            String name = nameGenerator.generateBeanName(beanDefinition, beanFactory);
                            beanFactory.registerBeanDefinition(name, beanDefinition);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
